﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Word = Microsoft.Office.Interop.Word;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
using System.Reflection;

namespace FormFiller
{
    public partial class ProjectInfoMain : Form
    {
        private InnovationProjectDirection p2projectDirection;
        private ProjectImplementationPeriod p3ProjectImplementationPeriod;
        private ProjectRealization p4ProjectRealization;
        private ProjectSupport p10ProjectSupport;

        private List<string> p5Analogs;
        private List<string> p5Tep;

        private MemberInfo anketaHead;
        private List<MemberInfo> anketaCommand;
        private List<string> anketaOrganizations;

        public ProjectInfoMain()
        {
            InitializeComponent();

            p5Analogs = new List<string>();
            p5Tep = new List<string>();

            anketaHead = new MemberInfo();
            anketaCommand = new List<MemberInfo>();
            anketaOrganizations = new List<string>();

            //bind
            updateP5Sources();

            updateOrganizationsSources();
            updateCommandSources();

            lbAnketaCommand.MouseDoubleClick += new MouseEventHandler(lbAnketaCommand_MouseDoubleClick);
            lbAnketaCommand.DisplayMember = "fio";

            updateHeadFio();

            initPage1();
            initPage2();
            initPage4();
            initPage6();
        }

        private void setRd2(InnovationProjectDirection dr)
        {
            switch (dr)
            {
                case InnovationProjectDirection.BIO:
                    rd2Bio.Checked = true;
                    break;
                case InnovationProjectDirection.IT:
                    rd2It.Checked = true;
                    break;
                case InnovationProjectDirection.MIF:
                    rd2Mif.Checked = true;
                    break;
                case InnovationProjectDirection.CHIM:
                    rd2Chim.Checked = true;
                    break;
                case InnovationProjectDirection.MASH:
                    rd2Mash.Checked = true;
                    break;
                case InnovationProjectDirection.ANOTHER:
                    rd2Another.Checked = true;
                    break;
            }
            rd2Changed(dr);
        }

        private void setRd3(ProjectImplementationPeriod pip)
        {
            switch (pip)
            {
                case ProjectImplementationPeriod.M1:
                    rd3_M1.Checked = true;
                    break;
                case ProjectImplementationPeriod._12:
                    rd3_12.Checked = true;
                    break;
                case ProjectImplementationPeriod._25:
                    rd3_25.Checked = true;
                    break;
                case ProjectImplementationPeriod._57:
                    rd3_57.Checked = true;
                    break;
                case ProjectImplementationPeriod._510:
                    rd3_510.Checked = true;
                    break;
                case ProjectImplementationPeriod.B10:
                    rd3_b10.Checked = true;
                    break;
                case ProjectImplementationPeriod.ANOTHER:
                    rd3_Another.Checked = true;
                    break;
            }
            rd3Changed(pip);
        }

        private void setRd4(ProjectRealization pr)
        {
            switch (pr)
            {
                case ProjectRealization.CREATENEW:
                    rd4CreateNew.Checked = true;
                    break;
                case ProjectRealization.ONEXISTING:
                    rd4OnExisting.Checked = true;
                    break;
                case ProjectRealization.NEWTECH:
                    rd4NewTech.Checked = true;
                    break;
                case ProjectRealization.ANOTHER:
                    rd4Another.Checked = true;
                    break;
            }
            rd4Changed(pr);
        }

        private void setRd10(ProjectSupport ps)
        {
            switch (ps)
            {
                case ProjectSupport.SCIENCE:
                    rd10Science.Checked = true;
                    break;
                case ProjectSupport.BUSYNESSPLAN:
                    rd10BusinessPlan.Checked = true;
                    break;
                case ProjectSupport.FINANCE:
                    rd10Finance.Checked = true;
                    break;
                case ProjectSupport.NOTNEEDED:
                    rd10NotNeeded.Checked = true;
                    break;
                case ProjectSupport.AREA:
                    rd10Area.Checked = true;
                    break;
                case ProjectSupport.ORGANIZATIONS:
                    rd10Organizations.Checked = true;
                    break;
                case ProjectSupport.PERSONAL:
                    rd10Personal.Checked = true;
                    break;
                case ProjectSupport.ANOTHER:
                    rd10Another.Checked = true;
                    break;
            }
            rd10Changed(ps);
        }

        public void initPage1()
        {
            rd2Bio.Checked = true;
            rd3_M1.Checked = true;
        }

        public void initPage2()
        {
            rd4CreateNew.Checked = true;
        }

        public void initPage4()
        {
            dgv6Sources.Rows.Add("Собственные средства", "111", "222");
            dgv6Sources.Rows.Add("Средства инвесторов", "333", "444");
        }

        public void initPage6()
        {
            rd10Science.Checked = true;
        }
        private void fillPresentation()
        {
            ProjectInfoData pid = saveDataToObject();
            //PowerPoint.Application powerPointApp = null;
            //PowerPoint.Presentation powerPointPresentation = null;
           // Object PPtemplatePathObject = 

            String strTemplate, strPic;
            strTemplate = Application.StartupPath + @"\\Template.pot";
            
            PowerPoint.Application objApp;
            PowerPoint.Presentations objPresSet;
            PowerPoint.Presentation objPres;
            PowerPoint.Slides objSlides;
            PowerPoint._Slide objSlide;
            PowerPoint.TextRange objTextRng;
                       
            //Create a new presentation based on a template.
            objApp = new PowerPoint.Application();
            objPres = null;
            objPresSet = objApp.Presentations;
            try
            {
                objPres = objPresSet.Open(strTemplate, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);
                objSlides = objPres.Slides;

                //Build Slide #1:
                objSlide = objSlides._Index(1);
                //Название вуза
                objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
                objTextRng.Text = pid.anketaOrganizations[0];
                //Название проекта
                objTextRng = objSlide.Shapes[2].TextFrame.TextRange;
                objTextRng.Text = pid.p4ProductName;
                objTextRng.ParagraphFormat.Alignment = PowerPoint.PpParagraphAlignment.ppAlignDistribute;
                //ФИО исполнителя
                objTextRng = objSlide.Shapes[3].TextFrame.TextRange;
                objTextRng.Text = pid.anketaCommand[0].fio;
                //ФИО руководителя
                objTextRng = objSlide.Shapes[4].TextFrame.TextRange;
                objTextRng.Text = pid.anketaHead.fio;

                //Build Slide #2:
                objSlide = objSlides._Index(2);
                //Ключевые слова
                objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
                objTextRng.Text = pid.p4TechDescription;
                //Тематическое направление проекта
                objTextRng = objSlide.Shapes[4].TextFrame.TextRange;
                string Direction = "";
                switch (pid.p2ProjectDirection)
                {
                    case InnovationProjectDirection.BIO:
                        Direction="- Биотехнологии";
                        break;
                    case InnovationProjectDirection.IT:
                        Direction="- Информационные технологии";
                        break;
                    case InnovationProjectDirection.MIF:
                        Direction="- Медицина и фармакология";
                        break;
                    case InnovationProjectDirection.CHIM:
                        Direction="- Химия, новые материалы, химические технологии";
                        break;
                    case InnovationProjectDirection.MASH:
                        Direction="- Машиностроение, электроника, приборостроение";
                        break;
                    case InnovationProjectDirection.ANOTHER:
                        Direction=pid.p2AnotherDirection;
                        break;
                }
                objTextRng.Text = Direction;
                //Build Slide #3:
                objSlide = objSlides._Index(3);
                //Описание
                objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
                objTextRng.Text = pid.p4ProjectDescription;
                //Build Slide #4:
                objSlide = objSlides._Index(4);
                //Интеллектуальная собственность
                objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
                objTextRng.Text = pid.p4Science;
                //Build Slide #5:
                objSlide = objSlides._Index(5);
                //комерция
                objTextRng = objSlide.Shapes[1].TextFrame.TextRange;
                objTextRng.Text = pid.p5Consumers;
            }
            catch (Exception error)
            {
                objPres.Close();
                objApp.Quit();
                objPres = null;
                objApp = null;
                throw error;
            }
            objApp.Visible = MsoTriState.msoTrue;
            
        }
        
        private void fillDocument()
        {
            ProjectInfoData pid = saveDataToObject();

            Word.Application app = null;
            Word.Document document = null;

            Object missingObj = System.Reflection.Missing.Value;
            Object trueObj = true;
            Object falseObj = false;

            app = new Word.Application();
            Object templatePathObject = Application.StartupPath + @"\\Template.dot";
            // если вылетим не этом этапе, приложение останется открытым
            try
            {
                document = app.Documents.Add(ref  templatePathObject, ref missingObj, ref missingObj, ref missingObj);

                //создадим список закладок
                Object bApplicationName = "applicationName";
                Object bApplicationDate = "applicationDate";

                Object bP1FullName = "p1FullName";
                Object bP1ShortName = "p1ShortName";

                Object bP2rdBIO = "p2rdBIO";
                Object bP2rdCHIM = "p2rdCHIM";
                Object bP2rdIT = "p2rdIT";
                Object bP2rdMASH = "p2rdMASH";
                Object bP2rdMIF = "p2rdMIF";
                Object bP2rdANOTHER = "p2rdANOTHER";
                Object bP2AnotherTxt = "p2AnotherTxt";

                Object bP3rdM1 = "p3rdM1";
                Object bP3rd_12 = "p3rd_12";
                Object bP3rd_25 = "p3rd_25";
                Object bP3rd_57 = "p3rd_57";
                Object bP3rd_510 = "p3rd_510";
                Object bP3rd_B10 = "p3rd_B10";
                Object bP3rd_ANOTHER = "p3rd_ANOTHER";
                Object bP3AnotherTxt = "p3AnotherTxt";

                Object bP4ProductName = "p4ProductName";
                Object bP4ProjectDescription = "p4ProjectDescription";
                Object bP4TechDescription = "p4TechDescription";
                Object bP4rdCREATENEW = "p4rdCREATENEW";
                Object bP4rdONEXISTING = "p4rdONEXISTING";
                Object bP4rdNEWTECH = "p4rdNEWTECH";
                Object bP4rdANOTHER = "p4rdANOTHER";
                Object bP4AnotherTxt = "p4AnotherTxt";
                Object bP4Science = "p4Science";

                Object bP5Table = "p5Table";
                Object bP5Consumers = "p5Consumers";
                Object bP5ProductName = "p5ProductName";
                Object bP5TableAnalogs = "p5Analogs";
                Object bP5TableTep = "p5Tep";

                Object bP6Table = "p6Table";
                Object bP6FullCost = "p6FullCost";
                Object bP6InvestorConditions = "p6InvestorConditions";
                Object bP6InvestorFunds = "p6InvestorFunds";
                Object bP6OwnConditions = "p6OwnConditions";
                Object bP6OwnFunds = "p6OwnFunds";

                Object bP7Time = "p7Time";

                Object bP8Law = "p8Law";

                Object bP9Examination = "p9Examination";

                Object bP10SCIENCE = "p10SCIENCE";
                Object bP10BUSYNESSPLAN = "p10BUSYNESSPLAN";
                Object bP10FINANCE = "p10FINANCE";
                Object bP10NOTNEEDED = "p10NOTNEEDED";
                Object bP10AREA = "p10AREA";
                Object bP10ORGANIZATIONS = "p10ORGANIZATIONS";
                Object bP10PERSONAL = "p10PERSONAL";
                Object bP10ANOTHER = "p10ANOTHER";
                Object bP10AnotherTxt = "P10AnotherTxt";//Большая буква P

                Object bP11Square = "p11Square";
                Object bP11Charact = "p11Charact";
                Object bP11PersonalCount = "p11PersonalCount";
                Object bP11Period = "p11Period";
                Object bP11Other = "p11Other";
                Object bP11FIOHead = "p11FIOHead";

                Object bAFioHead = "aFioHead";
                Object bAData = "aDATA";
                Object bAFIO = "aFIO";
                Object bACell = "aCell";
                Object bAPasport = "aPasport";
                Object bAQual = "aQual";
                Object bAMail = "aMail";
                Object bATeam = "aTeam";
                Object bAOrgan = "aOrgans";
                //заполним закладки
                //общие данные 
                Word.Range bookmarkRange = document.Bookmarks.get_Item(ref bApplicationName).Range;
                bookmarkRange.Text = pid.applicationName;
                bookmarkRange = document.Bookmarks.get_Item(ref bApplicationDate).Range;
                bookmarkRange.Text = pid.applicationDate.ToShortDateString();

                //пункт 1
                bookmarkRange = document.Bookmarks.get_Item(ref bP1FullName).Range;
                bookmarkRange.Text = pid.p1FullName;
                bookmarkRange = document.Bookmarks.get_Item(ref bP1ShortName).Range;
                bookmarkRange.Text = pid.p1ShortName;

                //пункт 2
                Object bP2Direction = null;
                switch (pid.p2ProjectDirection)
                {
                    case InnovationProjectDirection.BIO:
                        bP2Direction = bP2rdBIO;
                        break;
                    case InnovationProjectDirection.IT:
                        bP2Direction = bP2rdIT;
                        break;
                    case InnovationProjectDirection.MIF:
                        bP2Direction = bP2rdMIF;
                        break;
                    case InnovationProjectDirection.CHIM:
                        bP2Direction = bP2rdCHIM;
                        break;
                    case InnovationProjectDirection.MASH:
                        bP2Direction = bP2rdMASH;
                        break;
                    case InnovationProjectDirection.ANOTHER:
                        bP2Direction = bP2rdANOTHER;
                        break;
                }

                bookmarkRange = document.Bookmarks.get_Item(ref bP2Direction).Range;
                bookmarkRange.Font.Bold = -1;

                if (pid.p2ProjectDirection == InnovationProjectDirection.ANOTHER)
                {
                    //Заполняем текстом
                    bookmarkRange = document.Bookmarks.get_Item(ref bP2AnotherTxt).Range;
                    bookmarkRange.Text = pid.p2AnotherDirection;
                }

                //пункт 3
                Object bP3Period = null;
                switch (pid.p3ProjectImplPeriod)
                {
                    case ProjectImplementationPeriod.M1:
                        bP3Period = bP3rdM1;
                        break;
                    case ProjectImplementationPeriod._12:
                        bP3Period = bP3rd_12;
                        break;
                    case ProjectImplementationPeriod._25:
                        bP3Period = bP3rd_25;
                        break;
                    case ProjectImplementationPeriod._57:
                        bP3Period = bP3rd_57;
                        break;
                    case ProjectImplementationPeriod._510:
                        bP3Period = bP3rd_510;
                        break;
                    case ProjectImplementationPeriod.B10:
                        bP3Period = bP3rd_B10;
                        break;
                    case ProjectImplementationPeriod.ANOTHER:
                        bP3Period = bP3rd_ANOTHER;
                        break;
                }

                bookmarkRange = document.Bookmarks.get_Item(ref bP3Period).Range;
                bookmarkRange.Font.Bold = -1;

                if (pid.p3ProjectImplPeriod == ProjectImplementationPeriod.ANOTHER)
                {
                    //Заполняем текстом
                    bookmarkRange = document.Bookmarks.get_Item(ref bP3AnotherTxt).Range;
                    bookmarkRange.Text = pid.p3AnotherPeriod;
                }

                //пункт 4
                bookmarkRange = document.Bookmarks.get_Item(ref bP4ProductName).Range;
                bookmarkRange.Text = pid.p4ProductName;
                bookmarkRange = document.Bookmarks.get_Item(ref bP4ProjectDescription).Range;
                bookmarkRange.Text = pid.p4ProjectDescription;
                bookmarkRange = document.Bookmarks.get_Item(ref bP4TechDescription).Range;
                bookmarkRange.Text = pid.p4TechDescription;

                Object bP4Realization = null;
                switch (pid.p4Realization)
                {
                    case ProjectRealization.CREATENEW:
                        bP4Realization = bP4rdCREATENEW;
                        break;
                    case ProjectRealization.ONEXISTING:
                        bP4Realization = bP4rdONEXISTING;
                        break;
                    case ProjectRealization.NEWTECH:
                        bP4Realization = bP4rdNEWTECH;
                        break;
                    case ProjectRealization.ANOTHER:
                        bP4Realization = bP4rdANOTHER;
                        break;
                }

                bookmarkRange = document.Bookmarks.get_Item(ref bP4Realization).Range;
                bookmarkRange.Font.Bold = -1;

                if (pid.p4Realization == ProjectRealization.ANOTHER)
                {
                    //Заполняем текстом
                    bookmarkRange = document.Bookmarks.get_Item(ref bP4AnotherTxt).Range;
                    bookmarkRange.Text = pid.p4AnotherRealization;
                }

                bookmarkRange = document.Bookmarks.get_Item(ref bP4Science).Range;
                bookmarkRange.Text = pid.p4Science;

                //пункт 5
                bookmarkRange = document.Bookmarks.get_Item(ref bP5Consumers).Range;
                bookmarkRange.Text = pid.p5Consumers;

                //Построение таблицы на основе Аналогов и Признаков
                Word.Table p5Table;
                Word.Range TableRng = document.Bookmarks.get_Item(ref bP5Table).Range;
                p5Table = document.Tables.Add(TableRng, pid.p5Teps.Count + 2, pid.p5Analogs.Count + 3, ref missingObj, ref missingObj);
                //настройка стиля таблицы
                p5Table.AllowPageBreaks = true;
                p5Table.set_Style("Сетка таблицы");
                p5Table.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                //объеденение ячеек
                p5Table.Cell(1, 1).Merge(p5Table.Cell(2, 1));
                p5Table.Cell(1, 3 + pid.p5Analogs.Count).Merge(p5Table.Cell(2, 3 + pid.p5Analogs.Count));
                p5Table.Cell(1, 2).Merge(p5Table.Cell(1, 2 + pid.p5Analogs.Count - 1));

                //заполнение шапки              
                p5Table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);
                p5Table.Cell(1, 1).Range.Text = "Технико-экономические \nпоказатели (наименование и\n единицы измерения)";
                p5Table.Cell(1, 1).Range.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
                p5Table.Cell(1, 1).Range.ParagraphFormat.SpaceAfter = 0;
                p5Table.Cell(1, 2).Range.Text = "Наименования аналогов инновационной продукции";
                p5Table.Cell(1, 2).Range.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
                p5Table.Cell(1, 2).Range.ParagraphFormat.SpaceAfter = 0;
                p5Table.Cell(1, 3).Range.Text = "Наименование \nинновационной \nпродукции";
                p5Table.Cell(1, 3).Range.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
                p5Table.Cell(1, 3).Range.ParagraphFormat.SpaceAfter = 0;
                p5Table.Cell(1, 4).Range.Text = "В чем проявляются новые качества предлагаемого продукта по сравнению с аналогами";
                p5Table.Cell(1, 4).Range.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
                p5Table.Cell(1, 4).Range.ParagraphFormat.SpaceAfter = 0;

                //заполнение таблицы данными
                for (int i = 0; i < pid.p5Analogs.Count; i++)
                {
                    p5Table.Cell(2, 2 + i).Range.Text = pid.p5Analogs[i].ToString();
                }
                for (int i = 0; i < pid.p5Teps.Count; i++)
                {
                    p5Table.Cell(3 + i, 1).Range.Text = pid.p5Teps[i].ToString();
                }
                //заполнение наименования продукта
                p5Table.Cell(2, 2 + pid.p5Analogs.Count).Range.Text = pid.p5ProductName;
                //пункт 6
                bookmarkRange = document.Bookmarks.get_Item(ref bP6FullCost).Range;
                bookmarkRange.Text = pid.p6FullCost;
                bookmarkRange = document.Bookmarks.get_Item(ref bP6InvestorConditions).Range;
                bookmarkRange.Text = pid.p6InvestorConditions;
                bookmarkRange = document.Bookmarks.get_Item(ref bP6InvestorFunds).Range;
                bookmarkRange.Text = pid.p6InvestorFunds;
                bookmarkRange = document.Bookmarks.get_Item(ref bP6OwnConditions).Range;
                bookmarkRange.Text = pid.p6OwnConditions;
                bookmarkRange = document.Bookmarks.get_Item(ref bP6OwnFunds).Range;
                bookmarkRange.Text = pid.p6OwnFunds;
                //Построение таблицы на основе dgv6Jobs
                Word.Table p6Table;
                Word.Range wrdRng = document.Bookmarks.get_Item(ref bP6Table).Range;
                p6Table = document.Tables.Add(wrdRng, dgv6Jobs.RowCount, dgv6Jobs.ColumnCount, ref missingObj, ref missingObj);
                //настройка стиля таблицы
                //app.Visible = true;
                p6Table.AllowPageBreaks = true;
                p6Table.set_Style("Сетка таблицы");
                p6Table.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                //запись данных в таблицу
                int r, c;
                p6Table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);
                p6Table.Cell(1, 1).Range.Text = "№ п/п";
                p6Table.Cell(1, 2).Range.Text = "Наименование работ по основным этапам НИОКР";
                p6Table.Cell(1, 3).Range.Text = "Срок";
                p6Table.Cell(1, 4).Range.Text = "Затраты, \n тыс. руб.";
                p6Table.Cell(1, 4).Range.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
                p6Table.Cell(1, 4).Range.ParagraphFormat.SpaceAfter = 0;
                //Добавление последней строки ИТОГО
                if (dgv6Jobs.RowCount >= 1)
                {
                    p6Table.Rows.Add(p6Table.Rows[dgv6Jobs.RowCount]);
                }
                //запись данных из dataGridView в таблицу
                for (r = 1; r < dgv6Jobs.RowCount; r++)
                    for (c = 0; c < dgv6Jobs.ColumnCount; c++)
                    {
                        p6Table.Cell(r + 1, c + 1).Range.Text = dgv6Jobs[c, r - 1].Value.ToString();
                    }
                //объеденение ячейки ИТОГО     
                if (dgv6Jobs.RowCount >= 1)
                {
                    p6Table.Cell(dgv6Jobs.RowCount + 1, 1).Merge(p6Table.Cell(dgv6Jobs.RowCount + 1, 3));
                }
                //добавление ИТОГО
                p6Table.Cell(dgv6Jobs.RowCount + 1, 1).Range.Text = "ИТОГО";
                //пункт 7
                bookmarkRange = document.Bookmarks.get_Item(ref bP7Time).Range;
                bookmarkRange.Text = pid.p7Time;

                //пункт 8
                bookmarkRange = document.Bookmarks.get_Item(ref bP8Law).Range;
                bookmarkRange.Text = pid.p8Law;

                //пункт 9
                bookmarkRange = document.Bookmarks.get_Item(ref bP9Examination).Range;
                bookmarkRange.Text = pid.p9Examination;
                //пункт 10
                Object bP10Support = null;
                switch (pid.p10Support)
                {
                    case ProjectSupport.SCIENCE:
                        bP10Support = bP10SCIENCE;
                        break;
                    case ProjectSupport.BUSYNESSPLAN:
                        bP10Support = bP10BUSYNESSPLAN;
                        break;
                    case ProjectSupport.FINANCE:
                        bP10Support = bP10FINANCE;
                        break;
                    case ProjectSupport.NOTNEEDED:
                        bP10Support = bP10NOTNEEDED;
                        break;
                    case ProjectSupport.AREA:
                        bP10Support = bP10AREA;
                        break;
                    case ProjectSupport.ORGANIZATIONS:
                        bP10Support = bP10ORGANIZATIONS;
                        break;
                    case ProjectSupport.PERSONAL:
                        bP10Support = bP10PERSONAL;
                        break;
                    case ProjectSupport.ANOTHER:
                        bP10Support = bP10ANOTHER;
                        break;
                }

                bookmarkRange = document.Bookmarks.get_Item(ref bP10Support).Range;
                bookmarkRange.Font.Bold = -1;
                if (pid.p10Support == ProjectSupport.ANOTHER)
                {
                    //Заполняем текстом
                    bookmarkRange = document.Bookmarks.get_Item(ref bP10AnotherTxt).Range;
                    bookmarkRange.Text = pid.p10AnotherSupport;
                }
                //пункт 11
                bookmarkRange = document.Bookmarks.get_Item(ref bP11Square).Range;
                bookmarkRange.Text = pid.p11Square;
                bookmarkRange = document.Bookmarks.get_Item(ref bP11Charact).Range;
                bookmarkRange.Text = pid.p11Charact;
                bookmarkRange = document.Bookmarks.get_Item(ref bP11PersonalCount).Range;
                bookmarkRange.Text = pid.p11PersonalCount;
                bookmarkRange = document.Bookmarks.get_Item(ref bP11Period).Range;
                bookmarkRange.Text = pid.p11Period;
                bookmarkRange = document.Bookmarks.get_Item(ref bP11Other).Range;
                bookmarkRange.Text = pid.p11Other;
                bookmarkRange = document.Bookmarks.get_Item(ref bP11FIOHead).Range;
                bookmarkRange.Text = pid.anketaHead.fio;
                //АНКЕТА

                bookmarkRange = document.Bookmarks.get_Item(ref bAFioHead).Range;
                bookmarkRange.Text = pid.anketaHead.fio;
                bookmarkRange = document.Bookmarks.get_Item(ref bAData).Range;
                bookmarkRange.Text = pid.anketaHead.birthDay.ToShortDateString();
                bookmarkRange = document.Bookmarks.get_Item(ref bAFIO).Range;
                bookmarkRange.Text = pid.anketaHead.fio;
                bookmarkRange = document.Bookmarks.get_Item(ref bACell).Range;
                bookmarkRange.Text = pid.anketaHead.phone;
                bookmarkRange = document.Bookmarks.get_Item(ref bAPasport).Range;
                bookmarkRange.Text = pid.anketaHead.passportData;
                bookmarkRange = document.Bookmarks.get_Item(ref bAQual).Range;
                bookmarkRange.Text = pid.anketaHead.qualification;
                bookmarkRange = document.Bookmarks.get_Item(ref bAMail).Range;
                bookmarkRange.Text = pid.anketaHead.email;
                bookmarkRange = document.Bookmarks.get_Item(ref bATeam).Range;
                bookmarkRange.Font.Bold = -1;
                for (int i = 0;i<pid.anketaCommand.Count;i++)
                {
                    bookmarkRange.InsertAfter("\n"+(i+1).ToString()+
                        ". Ф.И.О.\t"+pid.anketaCommand[i].fio+
                        "\n Дата рождения:\t" + pid.anketaCommand[i].birthDay.ToShortDateString() +
                        "\n Квалификация:\t" + pid.anketaCommand[i].qualification +
                        "\n Паспортные данные:\t" + pid.anketaCommand[i].passportData +
                        "\n Контактный телефон:\t" + pid.anketaCommand[i].phone +
                        "\n Е-mail:\t" + pid.anketaCommand[i].email);                        
                }
                bookmarkRange = document.Bookmarks.get_Item(ref bAOrgan).Range;
                bookmarkRange.Font.Bold = -1;
                for (int i = 0; i < pid.anketaOrganizations.Count; i++)
                {
                    bookmarkRange.InsertAfter("\n" + (i + 1).ToString()+"."+ pid.anketaOrganizations[i]);
                }

            }
            catch (Exception error)
            {
                document.Close(ref falseObj, ref  missingObj, ref missingObj);
                app.Quit(ref missingObj, ref  missingObj, ref missingObj);
                document = null;
                app = null;
                throw error;
            }
            app.Visible = true;
        }

        //!-- 2 пункт
        private void rd2Another_CheckedChanged(object sender, EventArgs e)
        {
            rd2Changed(InnovationProjectDirection.ANOTHER);
        }

        private void rd2It_CheckedChanged(object sender, EventArgs e)
        {
            rd2Changed(InnovationProjectDirection.IT);
        }

        private void rd2Mif_CheckedChanged(object sender, EventArgs e)
        {
            rd2Changed(InnovationProjectDirection.MIF);
        }

        private void rd2Chim_CheckedChanged(object sender, EventArgs e)
        {
            rd2Changed(InnovationProjectDirection.CHIM);
        }

        private void rd2Mash_CheckedChanged(object sender, EventArgs e)
        {
            rd2Changed(InnovationProjectDirection.MASH);
        }

        private void rd2Bio_CheckedChanged(object sender, EventArgs e)
        {
            rd2Changed(InnovationProjectDirection.BIO);
        }

        private void rd2Changed(InnovationProjectDirection dir)
        {
            p2projectDirection = dir;
            txt2Another.Enabled = dir == InnovationProjectDirection.ANOTHER;
        }

        //!--- 2 пункт
        //!--- 3 пункт

        private void rd3_M1_CheckedChanged(object sender, EventArgs e)
        {
            rd3Changed(ProjectImplementationPeriod.M1);
        }

        private void rd3_12_CheckedChanged(object sender, EventArgs e)
        {
            rd3Changed(ProjectImplementationPeriod._12);
        }

        private void rd3_25_CheckedChanged(object sender, EventArgs e)
        {
            rd3Changed(ProjectImplementationPeriod._25);
        }

        private void rd3_57_CheckedChanged(object sender, EventArgs e)
        {
            rd3Changed(ProjectImplementationPeriod._57);
        }

        private void rd3_510_CheckedChanged(object sender, EventArgs e)
        {
            rd3Changed(ProjectImplementationPeriod._510);
        }

        private void rd3_b10_CheckedChanged(object sender, EventArgs e)
        {
            rd3Changed(ProjectImplementationPeriod.B10);
        }

        private void rd3Another_CheckedChanged(object sender, EventArgs e)
        {
            rd3Changed(ProjectImplementationPeriod.ANOTHER);
        }

        private void rd3Changed(ProjectImplementationPeriod per)
        {
            p3ProjectImplementationPeriod = per;
            txt3Another.Enabled = per == ProjectImplementationPeriod.ANOTHER;
        }

        //!--- 3 пункт
        //!--- 4 пункт

        private void rd4CreateNew_CheckedChanged(object sender, EventArgs e)
        {
            rd4Changed(ProjectRealization.CREATENEW);
        }

        private void rd4OnExisting_CheckedChanged(object sender, EventArgs e)
        {
            rd4Changed(ProjectRealization.ONEXISTING);
        }

        private void rd4NewTech_CheckedChanged(object sender, EventArgs e)
        {
            rd4Changed(ProjectRealization.NEWTECH);
        }

        private void rd4Another_CheckedChanged(object sender, EventArgs e)
        {
            rd4Changed(ProjectRealization.ANOTHER);
        }

        private void rd4Changed(ProjectRealization pr)
        {
            p4ProjectRealization = pr;
            txt4Another.Enabled = pr == ProjectRealization.ANOTHER;
        }

        //!--- 4 пункт
        //!--- 10 пункт

        private void rd10Science_CheckedChanged(object sender, EventArgs e)
        {
            rd10Changed(ProjectSupport.SCIENCE);
        }

        private void rd10BusinessPlan_CheckedChanged(object sender, EventArgs e)
        {
            rd10Changed(ProjectSupport.BUSYNESSPLAN);
        }

        private void rd10Finance_CheckedChanged(object sender, EventArgs e)
        {
            rd10Changed(ProjectSupport.FINANCE);
        }

        private void rd10NotNeeded_CheckedChanged(object sender, EventArgs e)
        {
            rd10Changed(ProjectSupport.NOTNEEDED);
        }

        private void rd10Area_CheckedChanged(object sender, EventArgs e)
        {
            rd10Changed(ProjectSupport.AREA);
        }

        private void rd10Organizations_CheckedChanged(object sender, EventArgs e)
        {
            rd10Changed(ProjectSupport.ORGANIZATIONS);
        }

        private void rd10Personal_CheckedChanged(object sender, EventArgs e)
        {
            rd10Changed(ProjectSupport.PERSONAL);
        }

        private void rd10Another_CheckedChanged(object sender, EventArgs e)
        {
            rd10Changed(ProjectSupport.ANOTHER);
        }

        private void rd10Changed(ProjectSupport ps)
        {
            p10ProjectSupport = ps;
            txt10Another.Enabled = ps == ProjectSupport.ANOTHER;
        }

        //!--- 10 пункт

        //!--- Анкета
        private void btnAnketaAddOrganization_Click(object sender, EventArgs e)
        {
            if (txtAnketaOrganiztaionName.Text.Length > 0)
            {
                anketaOrganizations.Add(txtAnketaOrganiztaionName.Text);
                updateOrganizationsSources();
                txtAnketaOrganiztaionName.Text = "";
            }
        }

        private void btnAnketaRemoveOrganization_Click(object sender, EventArgs e)
        {
            int selectedIndex = lbAnketaOrganizations.SelectedIndex;
            if (selectedIndex != -1)
            {
                anketaOrganizations.RemoveAt(selectedIndex);
                updateOrganizationsSources();
            }
        }

        private void btn5AddAnalog_Click(object sender, EventArgs e)
        {
            if (txt5AnalogsName.Text.Length > 0)
            {
                p5Analogs.Add(txt5AnalogsName.Text);
                txt5AnalogsName.Text = String.Empty;
                updateP5Sources();
            }
        }

        private void btn5RemoveAnalog_Click(object sender, EventArgs e)
        {
            int selectedIndex = lb5Analogs.SelectedIndex;
            if (selectedIndex != -1)
            {
                p5Analogs.RemoveAt(selectedIndex);
                updateP5Sources();
            }
        }

        private void btn5AddTec_Click(object sender, EventArgs e)
        {
            if (txt5TepName.Text.Length > 0)
            {
                p5Tep.Add(txt5TepName.Text);
                txt5TepName.Text = String.Empty;
                updateP5Sources();
            }
        }

        private void btn5RemoveTec_Click(object sender, EventArgs e)
        {
            int selectedIndex = lb5Tep.SelectedIndex;
            if (selectedIndex != -1)
            {
                p5Tep.RemoveAt(selectedIndex);
                updateP5Sources();
            }
        }

        private void btnAnketaFillHead_Click(object sender, EventArgs e)
        {
            //Открываем диалог
            MemberInfoChange changeWindow = new MemberInfoChange(anketaHead);
            changeWindow.ShowDialog();
            //Обновляем фио
            updateHeadFio();
        }

        public void updateHeadFio()
        {
            lblAnketaHeadFIO.Text = anketaHead.fio;
        }

        private void btnAnketaAddTeamMate_Click(object sender, EventArgs e)
        {
            anketaCommand.Add(new MemberInfo());
            updateCommandSources();
        }

        private void btnAnketaRemoveTeammate_Click(object sender, EventArgs e)
        {
            int selectedIndex = lbAnketaCommand.SelectedIndex;
            if (selectedIndex != -1)
            {
                anketaCommand.RemoveAt(selectedIndex);
                updateCommandSources();
            }
        }

        //!--- Анкета
        private void lbAnketaCommand_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int index = this.lbAnketaCommand.IndexFromPoint(e.Location);
            if (index != System.Windows.Forms.ListBox.NoMatches)
            {
                //Открываем диалог
                MemberInfoChange changeWindow = new MemberInfoChange(anketaCommand[index]);
                changeWindow.ShowDialog();
                //обновляем листбокс
                updateCommandSources();
            }
        }

        private void updateP5Sources()
        {
            lb5Analogs.DataSource = null;
            lb5Analogs.DataSource = p5Analogs;

            lb5Tep.DataSource = null;
            lb5Tep.DataSource = p5Tep;
        }

        private void updateCommandSources()
        {
            lbAnketaCommand.DataSource = null;
            lbAnketaCommand.DataSource = anketaCommand;
        }

        private void updateOrganizationsSources()
        {
            lbAnketaOrganizations.DataSource = null;
            lbAnketaOrganizations.DataSource = anketaOrganizations;
        }

        public ProjectInfoData saveDataToObject()
        {
            ProjectInfoData pid = new ProjectInfoData();

            //Заполняем данные

            //Общие данные
            pid.applicationName = txtApplicationName.Text;
            pid.applicationDate = dateApplication.Value;

            //Пункт 1
            pid.p1FullName = txt1FullName.Text;
            pid.p1ShortName = txt1ShortName.Text;

            //Пункт 2
            pid.p2ProjectDirection = p2projectDirection;
            pid.p2AnotherDirection = txt2Another.Text;

            //Пункт 3
            pid.p3ProjectImplPeriod = p3ProjectImplementationPeriod;
            pid.p3AnotherPeriod = txt3Another.Text;

            //Пункт 4
            pid.p4ProductName = txt4ProductName.Text;
            pid.p4ProjectDescription = txt4ProjectDescription.Text;
            pid.p4TechDescription = txt4TechDescription.Text;
            pid.p4Realization = p4ProjectRealization;
            pid.p4AnotherRealization = txt4Another.Text;
            pid.p4Science = txt4Science.Text;

            //Пункт 5
            pid.p5Consumers = txt5Consumers.Text;
            pid.p5ProductName = txt5ProductName.Text;
            pid.p5Analogs = new List<string>(p5Analogs);
            pid.p5Teps = new List<string>(p5Tep);

            //Пункт 6
            pid.p6FullCost = txt6FullCost.Text;

            pid.p6OwnFunds = dgv6Sources.Rows[0].Cells[1].Value.ToString();
            pid.p6OwnConditions = dgv6Sources.Rows[0].Cells[2].Value.ToString();

            pid.p6InvestorFunds = dgv6Sources.Rows[1].Cells[1].Value.ToString();
            pid.p6InvestorConditions = dgv6Sources.Rows[1].Cells[2].Value.ToString();

            pid.p6Jobs = new List<string[]>();

            //сохраняем данные из таблицы
            for (int i = 0; i < dgv6Jobs.RowCount - 1; i++)
            {
                DataGridViewRow row = dgv6Jobs.Rows[i];
                string[] rowArr = new string[dgv6Jobs.ColumnCount];

                for (int j = 0; j < dgv6Jobs.ColumnCount; j++)
                    rowArr[j] = row.Cells[j].Value != null ? row.Cells[j].Value.ToString() : null;

                pid.p6Jobs.Add(rowArr);
            }


            //Пункт 7
            pid.p7Time = txt7Time.Text;

            //Пункт 8
            pid.p8Law = txt8Law.Text;

            //Пункт 9
            pid.p9Examination = txt9Examination.Text;

            //Пункт 10
            pid.p10Support = p10ProjectSupport;
            pid.p10AnotherSupport = txt10Another.Text;

            //Пункт 11
            pid.p11Square = txt11Square.Text;
            pid.p11Charact = txt11Charact.Text;
            pid.p11PersonalCount = txt11PersonalCount.Text;
            pid.p11Period = txt11Period.Text;
            pid.p11Other = txt11Other.Text;

            //Анкета-приложение
            pid.anketaHead = new MemberInfo(anketaHead);
            pid.anketaCommand = new List<MemberInfo>(anketaCommand);
            pid.anketaOrganizations = new List<string>(anketaOrganizations);
            pid.anketaAddress = txtAnketaAddress.Text;
            pid.anketaPhone = txtAnketaPhone.Text;
            pid.anketaEmail = txtAnketaEmail.Text;

            return pid;
        }

        private void loadDataFromObject(ProjectInfoData data)
        {
            if (data == null)
                return;

            //Заполняем данные

            //Общие данные
            txtApplicationName.Text = data.applicationName;
            dateApplication.Value = data.applicationDate;

            //Пункт 1
            txt1FullName.Text = data.p1FullName;
            txt1ShortName.Text = data.p1ShortName;

            //Пункт 2
            setRd2(data.p2ProjectDirection);
            txt2Another.Text = data.p2AnotherDirection;

            //Пункт 3
            setRd3(data.p3ProjectImplPeriod);
            txt3Another.Text = data.p3AnotherPeriod;

            //Пункт 4
            txt4ProductName.Text = data.p4ProductName;
            txt4ProjectDescription.Text = data.p4ProjectDescription;
            txt4TechDescription.Text = data.p4TechDescription;
            setRd4(data.p4Realization);
            txt4Another.Text = data.p4AnotherRealization;
            txt4Science.Text = data.p4Science;

            //Пункт 5
            txt5Consumers.Text = data.p5Consumers;
            txt5ProductName.Text = data.p5ProductName;
            p5Analogs = data.p5Analogs;
            p5Tep = data.p5Teps;
            updateP5Sources();

            //Пункт 6
            txt6FullCost.Text = data.p6FullCost;

            dgv6Sources.Rows[0].Cells[1].Value = data.p6OwnFunds;
            dgv6Sources.Rows[0].Cells[2].Value = data.p6OwnConditions;

            dgv6Sources.Rows[1].Cells[1].Value = data.p6InvestorFunds;
            dgv6Sources.Rows[1].Cells[2].Value = data.p6InvestorConditions;

            //записываем данные в таблицу
            dgv6Jobs.Rows.Clear();

            for (int i = 0; i < data.p6Jobs.Count; i++)
            {
                int id = dgv6Jobs.Rows.Add();
                string[] rowArr = data.p6Jobs[i];

                for (int j = 0; j < dgv6Jobs.ColumnCount; j++)
                {
                    dgv6Jobs.Rows[id].Cells[j].Value = rowArr[j];
                }
            }

            //Пункт 7
            txt7Time.Text = data.p7Time;

            //Пункт 8
            txt8Law.Text = data.p8Law;

            //Пункт 9
            txt9Examination.Text = data.p9Examination;

            //Пункт 10
            setRd10(data.p10Support);
            txt10Another.Text = data.p10AnotherSupport;

            //Пункт 11
            txt11Square.Text = data.p11Square;
            txt11Charact.Text = data.p11Charact;
            txt11PersonalCount.Text = data.p11PersonalCount;
            txt11Period.Text = data.p11Period;
            txt11Other.Text = data.p11Other;

            //Анкета-приложение
            anketaHead = new MemberInfo(data.anketaHead);
            updateHeadFio();

            anketaCommand = new List<MemberInfo>(data.anketaCommand);
            anketaOrganizations = new List<string>(data.anketaOrganizations);

            updateCommandSources();
            updateOrganizationsSources();

            txtAnketaAddress.Text = data.anketaAddress;
            txtAnketaPhone.Text = data.anketaPhone;
            txtAnketaEmail.Text = data.anketaEmail;
        }

        private void openMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "ProjectInfo File (*.pidf)|*.pidf|All Files|";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string fileName = dlg.FileName;

                FileStream str = File.Open(fileName, FileMode.Open);
                BinaryFormatter deserializer = new BinaryFormatter();
                ProjectInfoData pid = (ProjectInfoData)deserializer.Deserialize(str);
                str.Close();

                loadDataFromObject(pid);
            }
        }

        private void saveMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "ProjectInfo File (*.pidf)|*.pidf|All Files|";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string fileName = dlg.FileName;

                //сохраняем данные в объект и записываем в файл
                ProjectInfoData data = saveDataToObject();

                Stream str = File.Create(fileName);
                BinaryFormatter serializer = new BinaryFormatter();
                serializer.Serialize(str, data);
                str.Close();
            }
        }

        private void exportMenuItem_Click(object sender, EventArgs e)
        {
            fillDocument();
        }

        private void exportPPTMenuItem_Click(object sender, EventArgs e)
        {
            fillPresentation();
        }
    }
}
